package com.shipwe.loans.utils.dialog

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.shipwe.adapter.ShipweOnItemChildClickListener
import com.shipwe.loans.R
import com.shipwe.loans.configs.ShipweConfigs
import com.shipwe.loans.databinding.DialogCustomerBinding
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.HttpHelper
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.pro.ShipweDialog
import com.shipwe.loans.ui.adapter.CustomerAdapter
import com.shipwe.loans.utils.ShipweToastManager
import com.shipwe.loans.utils.event.AppEventPointHelper
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import com.shipwe.permission.OnPermissionCallback
import com.shipwe.permission.Permission
import com.shipwe.permission.XXPermissions
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/15 10:29
 * @Annotation：联系客服Dialog
 */
class CustomerDialog(context: Context) : ShipweDialog(context) {
    lateinit var binding: DialogCustomerBinding
    private var callback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //产品名称
    private var pName = ShipweConfigs.SHIPWE_APPNAME
    //产品Token
    private var pToken = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_TOKEN)
    //客服联系方式列表
    private var customerAdapter: CustomerAdapter? = null

    override fun getRootView(): View {
        binding = DialogCustomerBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initCustomerListView()
    }

    override fun initListener() {
        setOnClickListener(binding.customerClose)
    }

    override fun initData() {
        //主产品
        if (this.pName == ShipweConfigs.SHIPWE_APPNAME){
            val commonInfo = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_COMMON)
            if (commonInfo.isEmpty()){
                loadCustomerContactListAction()
                return
            }
            val data = JSONObject(commonInfo)
            setCustomerContactData(data)
        } else {
            loadCustomerContactListAction()
        }
    }

    override fun onViewClick(v: View?) {
        dismiss()
    }

    /**
     * 事件备注
     */
    fun setCustomerEventRemark(remark: String): CustomerDialog{
        this.eventRemark = remark
        return this
    }

    /**
     * 对应的产品名称
     */
    fun setCustomerProductName(name: String): CustomerDialog{
        if (name.isNotEmpty()){
            this.pName = name
        }
        return this
    }

    /**
     * 对应的产品Token
     */
    fun setCustomerProductToken(token: String): CustomerDialog{
        if (pToken.isNotEmpty()){
            this.pToken = token
        }
        return this
    }

    /**
     * 设置监听回调
     */
    fun setCustomerClickCallback(callback: IDialogCallback): CustomerDialog{
        this.callback = callback
        return this
    }

    fun setCustomerCancelable(flag: Boolean): CustomerDialog{
        setCancelable(flag)
        return this
    }

    fun setCustomerCanceledOnTouchOutside(flag: Boolean): CustomerDialog{
        setCanceledOnTouchOutside(flag)
        return this
    }

    /**
     * 初始化Tab列表
     */
    private fun initCustomerListView() {
        binding.customerTime.visibility = View.GONE
        binding.customerListView.visibility = View.GONE
        binding.customerListView.layoutManager = LinearLayoutManager(context)
        customerAdapter = CustomerAdapter(binding.customerListView)
        binding.customerListView.adapter = customerAdapter
        binding.customerListView.itemAnimator = DefaultItemAnimator()
        customerAdapter!!.setOnItemChildClickListener(ShipweOnItemChildClickListener { _, childView, position ->
            val item = customerAdapter!!.getItem(position)
            if (childView.id == R.id.customerFun) {//切换item
                when (item.optString("type")) {
                    "MOBILE" -> {//电话
                        if (XXPermissions.isGranted(context, Permission.CALL_PHONE)) {
                            onCustomerMobileCallAction(item)
                        } else {
                            XXPermissions.with(context)
                                .permission(Permission.CALL_PHONE)
                                .request(object : OnPermissionCallback {
                                    override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_SYSTEM_AGREE, Permission.CALL_PHONE)
                                        onCustomerMobileCallAction(item)
                                    }
                                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_SYSTEM_DENY, Permission.CALL_PHONE)
                                        XXPermissions.startPermissionActivity(context, Permission.CALL_PHONE)
                                    }
                                })
                        }
                    }

                    else -> {//邮箱
                        onCustomerEmailCopyAction(item)
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    private fun loadCustomerContactListAction(){
        val params = JSONObject().apply {
            put("path",ApiService.API_PATH.SHIPWE_API_APP_INFO_PATH)
            put("product",pName)
            put("token",pToken)
        }
        val httpUrl = ApiService.getHttpUrl()
        HttpHelper.post(httpUrl,params,this,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        //保存所有数据
                        if (obj != null) {
                            setCustomerContactData(obj)
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                ShipweToastManager.showShortText(context,error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    private fun setCustomerContactData(data: JSONObject){
        binding.customerTime.visibility = View.VISIBLE
        binding.customerListView.visibility = View.VISIBLE
        val contactList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        if (customize != null){
            val mobileList = customize.optString("mobile").split(",")
            for (i in mobileList.indices){
                val obj = JSONObject()
                obj.put("type","MOBILE")
                obj.put("value", mobileList[i])
                contactList.add(obj)
            }
            val emailList = customize.optString("email").split(",")
            for (i in emailList.indices){
                val obj = JSONObject()
                obj.put("type","EMAIL")
                obj.put("value", emailList[i])
                contactList.add(obj)
            }
        }
        customerAdapter!!.data = contactList

        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workDate = "Monday to Sunday"
        var workTime = "9:30am to 19:30pm."
        val customData = customize!!.optJSONObject("customData")
        if (customData != null){
            if (!customData.has("workDate") || !customData.has("workTime")){
                val commonCustomData = CustomConfigsHelper.getShipweCustomData()
                if (commonCustomData != null) {
                    customData.put("workDate",commonCustomData.optString("workDate"))
                    customData.put("workTime",commonCustomData.optString("workTime"))
                }
            }
            workDate = customData.optString("workDate")
            workTime = customData.optString("workTime")
        }
        binding.customerTime.text = String.format(context.getString(R.string.customer_time),"$workDate,$workTime")
    }

    /**
     * 复制
     */
    private fun onCustomerEmailCopyAction(item: JSONObject){
        val type = item.optString("type")
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_KEFU_COPY,type + "：" + item.optString("value"))
        // 获取剪贴板管理器
        val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", item.optString("value"))
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        ShipweToastManager.showShortText(context, context.getString(R.string.customer_email_copy_success))
    }

    /**
     * 拨号
     */
    private fun onCustomerMobileCallAction(item: JSONObject){
        val type = item.optString("type")
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_KEFU_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        context.startActivity(callIntent)
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    override fun onStart() {
        super.onStart()
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.DIALOG.SHIPWE_DIALOG_CUSTOMER_SHOW, eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.cancelTag(this)
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.DIALOG.SHIPWE_DIALOG_CUSTOMER_DISMISS, eventRemark)
    }
}